package mysql

import (
	"data-transfer/domain"
	"data-transfer/global"
	"data-transfer/plugins"
	"data-transfer/transfer"
	"fmt"
	"go.uber.org/zap"
	"time"
)
import "context"

//GetAllQNewsAnimPM 取得所有快讯证券新闻
func (mdb *db) GetAllQNewsAnimPM(ctx context.Context) ([]*domain.T_QNEWS_ANIMPM, error) {
	var results []*domain.T_QNEWS_ANIMPM
	err := mdb.db.NewSession().Distinct("SOURCEKEY").Where("ISVALID = ?", 1).Find(&results)
	return results, err
}

//GetAllQNewsAnimPM4Fix 获取时间间隔范围内的证券快讯新闻信息
func (mdb *db) GetAllQNewsAnimPM4Fix(ctx context.Context, startDate string, endDate string) ([]string, error) {
	var sourceKeys []string
	sql := "select distinct SOURCEKEY from T_QNEWS_ANIMPM where UNIX_TIMESTAMP(ENTRYDT) between UNIX_TIMESTAMP('" + startDate + "') and UNIX_TIMESTAMP('" + endDate + "')"
	datas, err := mdb.db.QueryString(sql)
	if err != nil {
		global.LOG.Error("查询快讯证券新闻表【T_QNEWS_ANIMPM】信息出错:", zap.Any("err", err))
		return nil, err
	}

	for _, d := range datas {
		sourceKey := d["SOURCEKEY"]
		sourceKeys = append(sourceKeys, sourceKey)
	}
	return sourceKeys, err
}

//GetSkDailyPricesByTrCode 根据trCode 获取涨跌、涨跌值等股票历史交易信息
func (mdb *db) GetSkDailyPricesByTrCode(ctx context.Context, trCode string) ([]*domain.TQ_QT_SKDAILYPRICE, error) {
	var results []*domain.TQ_QT_SKDAILYPRICE
	err := mdb.db.NewSession().Where("ISVALID=? and SECODE = ?", 1, trCode).Desc("ID").Find(&results)
	return results, err
}

//GetSkDailyPrices 获取涨跌、涨跌值等股票历史交易信息
func (mdb *db) GetSkDailyPrices(ctx context.Context) ([]*domain.TQ_QT_SKDAILYPRICE, error) {
	var results []*domain.TQ_QT_SKDAILYPRICE
	//err := mdb.db.NewSession().Where("ISVALID=? ", 1).Desc("ID").Find(&results)

	datas, err := mdb.db.Query("select t1.* from TQ_QT_SKDAILYPRICE t1,(SELECT SECODE,max(TRADEDATE) as TRADEDATE from  TQ_QT_SKDAILYPRICE GROUP BY SECODE )as t2 where  t1.SECODE = t2.SECODE  and  t1.TRADEDATE = t2.TRADEDATE order by TRADEDATE DESC")
	if err != nil {
		global.LOG.Error("查询股票历史日交易【TQ_QT_SKDAILYPRICE】信息出错:", zap.Any("err", err))
		return nil, err
	}
	for _, d := range datas {
		r := new(domain.TQ_QT_SKDAILYPRICE)

		tradeDate := fmt.Sprintf("%s", d["TRADEDATE"])
		secode := fmt.Sprintf("%s", d["SECODE"])
		exchange := fmt.Sprintf("%s", d["EXCHANGE"])
		sename := fmt.Sprintf("%s", d["SENAME"])
		tclose := fmt.Sprintf("%s", d["TCLOSE"])
		change := fmt.Sprintf("%s", d["CHANGE"])
		pchg := fmt.Sprintf("%s", d["PCHG"])

		r.Sename = sename       //证券名称
		r.Change = change       //涨跌
		r.Pchg = pchg           //涨跌幅
		r.Secode = secode       //证券内码
		r.Tclose = tclose       //收盘价
		r.Tradedate = tradeDate //交易日期
		r.Exchange = exchange   //交易市场

		results = append(results, r)
	}

	return results, err
}

func setSymbol(sp []*domain.TQ_QT_SKDAILYPRICE, bs []*domain.TQ_SK_BASICINFO) {
	for _, p := range sp {
		for _, n := range bs {
			if p.Secode == n.Secode {
				p.Symbol = n.Symbol
				p.Exchange = n.Exchange
				break
			}
		}
	}
}

//GetAllSkDailyPriceAndInsert 查询证券涨跌数据并分批次插入
func (mdb *db) GetAllSkDailyPriceAndInsert(ctx context.Context, infos []*domain.TQ_SK_BASICINFO, t plugins.TargetStore) (int64, error) {
	var (
		affected int64
		err      error
	)

	var rows []*domain.SK_INFO_CHANGE //每一个TrCode对应一个结果集

	dailyPrices, err1 := mdb.GetSkDailyPrices(ctx)
	if err1 != nil {
		global.LOG.Error("获取 TQ_QT_SKDAILYPRICE 股票历史日交易 数据出错:", zap.Any("err", err))
		return 0, err1
	}
	setSymbol(dailyPrices, infos)

	for _, p := range dailyPrices {
		r := new(domain.SK_INFO_CHANGE)
		r.Symbol = p.Symbol
		r.Sename = p.Sename //证券名称
		r.Change = p.Change //涨跌
		r.Pchg = p.Pchg     //涨跌幅
		r.Exchange = transfer.TransferExchane(p.Exchange)

		rows = append(rows, r)
	}

	global.LOG.Info("获取 TQ_QT_SKDAILYPRICE 股票历史日交易 数据数量:", zap.Int("nums", len(rows)))

	if len(rows) > 0 {
		affected, err = t.InsertSkInfoChange(ctx, rows)

	}

	return affected, err
}

//GetAllSkDailyPrice 获取证券涨跌数据信息
func (mdb *db) GetAllSkDailyPrice(ctx context.Context, news []*domain.T_QNEWS_ANIMPM) ([]*domain.SK_INFO_CHANGE, error) {
	var results []*domain.SK_INFO_CHANGE

	for _, n := range news {
		symbol := n.Symbol

		trCode := n.Trcode //证券市场内码

		dailyPrices, err := mdb.GetSkDailyPricesByTrCode(ctx, trCode)
		if err != nil {
			global.LOG.Error("获取 TQ_QT_SKDAILYPRICE 股票历史日交易 数据出错:", zap.Any("err", err))
			return nil, err
		}

		for _, p := range dailyPrices {
			r := new(domain.SK_INFO_CHANGE)
			r.Symbol = symbol
			r.Sename = p.Sename //证券名称
			r.Change = p.Change //涨跌
			r.Pchg = p.Pchg     //涨跌幅

			results = append(results, r)
		}

	}
	return results, nil
}

//GetQNewsBasicBySourceKey 根据sourceKey取得所有快讯新闻基本信息
func (mdb *db) GetQNewsBasicBySourceKey(ctx context.Context, sourceKey string) ([]*domain.T_QNEWS_BASIC, error) {
	var results []*domain.T_QNEWS_BASIC
	//err := mdb.db.NewSession().Where("PUBLISHTIME > DATE_SUB(CURDATE(), INTERVAL 1 MONTH) and ISVALID=? and SOURCEKEY = ?", 1, sourceKey).Desc("ID").Find(&results)
	err := mdb.db.NewSession().Where("PUBLISHTIME > DATE_SUB(CURDATE(), INTERVAL 1 MONTH) and ISVALID=? and SOURCEKEY = ?", 1, sourceKey).Find(&results) // 取消排序
	return results, err
}

func setExchange(n *domain.T_QNEWS_ANIMPM, basicInfos []*domain.TQ_SK_BASICINFO) {
	for _, b := range basicInfos {
		if n.Symbol == b.Symbol {
			n.Exchange = b.Exchange
		}
	}
}

//FixNews 补充快讯数据
func (mdb *db) FixNews(ctx context.Context, sourceKeys []string, t plugins.TargetStore) error {
	var keys []string
	var rows []*domain.NEWS

	for _, k := range sourceKeys {

		//先判断F10本地数据源是否有sourceKey的数据,
		has, err := t.HasNews(k)
		if err != nil {
			global.LOG.Error("根据 SourceKey 判断 相应快讯新闻是否存在出错:", zap.Any("err", err))
			return err
		}
		// 过滤掉已经存在的数据
		if !has {
			keys = append(keys, k)
		}
	}

	for _, k := range keys {

		sourceKey := k //取得每一条新闻的sourceKey
		newBasics, err := mdb.GetQNewsBasicBySourceKey(ctx, sourceKey)
		if err != nil {
			global.LOG.Error("根据 SourceKey 获取 T_QNEWS_BASIC 快讯新闻基本信息数据出错:", zap.Any("err", err))
			return err
		}
		for _, b := range newBasics {
			r := new(domain.NEWS)

			if b.PublishtimeMet.IsZero() { //如果发布时间为空，使用人工修复的发布时间
				r.Publishtime = b.Publishtime
			} else {
				r.Publishtime = b.PublishtimeMet //人工修正发布时间(EDR/终端)
			}
			r.NewstitleMe = b.NewstitleMe   //人工处理后的标题(EDR)
			r.NewstextMe = b.NewstextMe     //人工处理后的正文(EDR)
			r.NewssourceMe = b.NewssourceMe //人工处理后的来源(EDR)
			r.Label = 0                     //默认为0
			r.LabelOrder = 0                //默认排序为0
			r.Titlefontstyle = 0            //默认为0
			r.PublishStatus = 0             //未发布
			r.Views = 0                     //点击数
			r.Shares = 0                    //分享数
			r.Collections = 0               //收藏数
			r.Sorttime = time.Now()         //排序时间
			r.Sourcekey = sourceKey         //业务主键
			// 构造ID为sourceKey
			r.Id = sourceKey

			rows = append(rows, r)
		}
	}

	if len(rows) > 0 {
		newNums, e := t.InsertNews(ctx, rows)
		if e != nil {
			global.LOG.Fatal("补充快讯新闻基本信息数据失败:", zap.Any("err", e))
			return e
		}
		global.LOG.Info("补充快讯新闻基本信息数据条数:", zap.Int64("nums", newNums))
	}

	return nil

}

//GetAllNews 取得所有快讯信息
func (mdb *db) GetAllNews(ctx context.Context, news []*domain.T_QNEWS_ANIMPM) ([]*domain.NEWS, error) {
	var rows []*domain.NEWS

	for _, v := range news {

		//	setExchange(v, basicInfos)

		var tempRows []*domain.NEWS

		symbol := v.Symbol
		//trCode := v.Trcode //证券市场内码
		sourceKey := v.Sourcekey //取得每一条新闻的sourceKey
		//exchange := v.Exchange
		exchange := "" //资讯查询不涉及exchange

		newBasics, err := mdb.GetQNewsBasicBySourceKey(ctx, sourceKey)
		if err != nil {
			global.LOG.Error("根据 SourceKey 获取 T_QNEWS_BASIC 快讯新闻基本信息数据出错:", zap.Any("err", err))
			return nil, err
		}

		for _, b := range newBasics {
			r := new(domain.NEWS)
			r.Symbol = symbol
			r.Exchange = transfer.TransferExchane(exchange) //市场代码
			if b.PublishtimeMet.IsZero() {                  //如果发布时间为空，使用人工修复的发布时间
				r.Publishtime = b.Publishtime
			} else {
				r.Publishtime = b.PublishtimeMet //人工修正发布时间(EDR/终端)
			}
			r.NewstitleMe = b.NewstitleMe   //人工处理后的标题(EDR)
			r.NewstextMe = b.NewstextMe     //人工处理后的正文(EDR)
			r.NewssourceMe = b.NewssourceMe //人工处理后的来源(EDR)
			r.Label = 0                     //默认为0
			r.LabelOrder = 0                //默认排序为0
			r.Titlefontstyle = 0            //默认为0
			r.PublishStatus = 0             //未发布
			r.Views = 0                     //点击数
			r.Shares = 0                    //分享数
			r.Collections = 0               //收藏数
			r.Sorttime = time.Now()         //排序时间
			r.Sourcekey = sourceKey         //业务主键

			// 构造ID为sourceKey
			r.Id = sourceKey

		}

		//累加
		rows = append(rows, tempRows...)
	}
	return rows, nil
}
